<template>
	<view class="reg-page">
		<view style="padding: 0 10px;margin-top: 10px;">
			<view class="form-sty">
				<text class="input-title">头像</text>
				<uni-file-picker :disabled="btnFla" class="img-sty" :auto-upload="false" limit="1" mode="grid" :disablePreview="false"
					v-model="imgList" file-mediatype="image" :sizeType="sizeType" ref="imgs" @select="imgSelect"
					@progress="imgProgress" @success="imgSuccess" @fail="imgFail" @delete="delImg">
					<!-- <textstyle="font-size: 20px;font-weight: 500;">+</text> -->
				</uni-file-picker>
			</view>
			<view class="form-sty">
				<text class="input-title bi-shu-sty">姓名</text>
				<input v-if="!formData._id" class="input-sty" type="text" v-model="formData.userNm" :maxlength="4" placeholder="请输入全名" :disabled="btnFla">
				<text v-else class="input-sty is-disabled">{{formData.userNm}}</text>
			</view>
			<view class="form-sty">
				<text class="input-title bi-shu-sty">手机号</text>
				<input v-if="!formData._id" class="input-sty" type="text" v-model="formData.phone" :maxlength="11" placeholder="手机号" :disabled="btnFla">
				<text v-else class="input-sty is-disabled">{{formData.phone}}</text>
			</view>
			<view class="form-sty">
				<text class="input-title ">性别</text>
				<uni-data-select class="input-sty" @change="getGender" v-model="formData.gender"
					:localdata="items" :clear="false" :disabled="btnFla"/>
			</view>
<!-- 			<view class="form-sty">
				<text class="input-title bi-shu-sty">证件号</text>
				<input class="input-sty" type="text" v-model="formData.identityCardNo" :maxlength="18" placeholder="证件号" :disabled="btnFla">
			</view> -->
<!-- 			<view class="form-sty">
				<text class="input-title">邮箱</text>
				<input class="input-sty" type="text" v-model="formData.email" placeholder="邮箱" :disabled="btnFla">
			</view> -->
			<view v-if="btnFla" style="margin: 150px auto;text-align: center;">
				<view class="btn-area" @click="editBtn" style="display: inline-block;">
					<view class="btn-sty" style="background: #fc993b;color:#fff;">编辑</view>
				</view>
			</view>
			<view style="display: flex;margin-top: 35px;" v-else>
				<view class="btn-area" @click="restBtn">
					<view class="btn-sty">重置</view>
				</view>
				<view class="btn-area" @click="confirmBtn">
					<view class="btn-sty" style="background: #fc993b;color:#fff;">确认</view>
				</view>

			</view>

		</view>
	</view>
</template>

<script>
	import {cheackUser,verifyForm,checkFontRule} from '@/utils/baseFn.js';
	const db = uniCloud.database()
	const items = [{
			value: '0',
			text: '女'
		},
		{
			value: '1',
			text: '男'
		}
	]
	export default {
		data() {
			return {
				formData: {
					portrait: '',
					userNm: '',
					gender: '',
					phone: '',
					identityCardNo: '',
					email: ''
				},
				imgList: [],
				sizeType: ['original', 'compressed'],
				items: items,
				btnFla: false
			}
		},
		onLoad(e) {
			const _this = this
			uni.getStorage({
				key: 'userInfo',
				success: function(res) {
					if (res.data) {
						const file = res.data.portrait.split(',')
						_this.formData = res.data
						_this.imgList = [{
							fileID: `${_this.$baseImgUrl}${file[0]}`,
							url: `${_this.$baseImgUrl}${file[0]}`,
							name: file[1]
						}]
						_this.btnFla = true
					}
				},
				fail: function(res) {
				}
			})
		},
		created() {},
		mounted() {},
		methods: {
			// 手动上传
			upload() {
				// 插件上传
				this.$refs.imgs.upload()
			},
			// 获取上传状态
			imgSelect(e, index = 0) {
				console.log('选择文件：', e)
				e.tempFiles.map(item => {
					if (`jpg,jpeg,png`.indexOf(item.extname) > -1) {
						if (item.size > 522183) {
							this.compress(item, index);
						} else {
							this.upload()
						}
					} else {
						this.upload()
					}
				})
			},
			// 删除附件
			delImg(e) {
				const _this = this
				let str = '删除后该图片将无法在页面展示，请谨慎删除！'
				let tt = `删除图片？`
				if (this.btnFla) {
					str = '点击编辑按钮后方可修改！'
					tt = '不能删除！'
				}
				uni.showModal({
					title: tt,
					content: str,
					success: async (res) => {
						if (res.confirm) {
							// const arr = _this.formData.imgs
							// arr.map((item, index) => {
							// 	if (item.fileID === e.tempFile.fileID) {
							// 		arr.splice(index, 1)
							// 	}
							// })
							// _this.imgList = arr
							// console.log(arr)
							if (_this.btnFla) {
								const file = this.formData.portrait.split(',')
								_this.imgList = [{
									fileID: `${_this.$baseImgUrl}${file[0]}`,
									url: `${_this.$baseImgUrl}${file[0]}`,
									name: file[1]
								}]
								return
							} else {
								const annexFn = uniCloud.importObject('annex-del-fn')
								await annexFn.delFileFn([e.tempFile.fileID])
								_this.formData.portrait = ''
							}
							
						} else {
							const file = this.formData.portrait.split(',')
							_this.imgList = [{
								fileID: `${_this.$baseImgUrl}${file[0]}`,
								url: `${_this.$baseImgUrl}${file[0]}`,
								name: file[1]
							}]
						}
					},
					fail: () => {
						uni.showToast({
							title: '删除失败',
							icon: 'none'
						})
					}
				})
			},
			// 获取上传进度
			imgProgress(e) {
				console.log('上传进度：', e)
			},
			// 上传成功
			imgSuccess(e) {
				const url = e.tempFilePaths[0].split('/')
				this.formData.portrait = `${url[url.length - 1]},${e.tempFiles[0].name}`
				console.log('上传成功', e, this.formData.portrait)
			},
			// 上传失败
			imgFail(e) {
				console.log('上传失败：', e)
			},
			compress(r, index) { // 图片压缩
				var that = this;
				const num = r.size > 2251836 ? 3 : r.size < 1225836 ? 34 : 8
				console.log(r.size, '>522183原图大小', num, '压缩比例');
				if (r.size) {
					wx.compressImage({
						src: r.path,
						quality: num, // 0-100,越高却清晰
						success(res) {
							that.SizeImg(r, res, index, num);
						}
					})
				}
			},
			SizeImg(r, res, n, num) { // 查询图片大小
				let that = this;
				const arr = []
				wx.getFileInfo({ //查询压缩后的图片大小
					filePath: res.tempFilePath,
					success(ys) {
						let h = that.$refs.imgs.filesList[n].image.height * ((100 - num) / 100)
						let w = that.$refs.imgs.filesList[n].image.width * ((100 - num) / 100)
						console.log('压缩后的文件大小：' + ys.size);
						console.log('压缩后的临时路径：' + res.tempFilePath);
						that.$refs.imgs.filesList[n].path = res.tempFilePath
						that.$refs.imgs.filesList[n].size = ys.size
						that.$refs.imgs.filesList[n].url = res.tempFilePath
						that.$refs.imgs.filesList[n].image = {
							height: h,
							location: res.tempFilePath,
							width: w
						}
						that.$refs.imgs.filesList[n].width = w
						that.$refs.imgs.filesList[n].height = h
						that.$refs.imgs.filesList[n].location = res.tempFilePath
						that.upload()
					}
				})
			},
			getGender (e) {
				console.log(e)
			},
			editBtn () {
				this.btnFla = false
			},
			restBtn() {
				this.formData = {
					portrait: '',
					userNm: '',
					gender: '',
					phone: '',
					identityCardNo: '',
					email: ''
				}
			},
			confirmBtn() {
				const _this = this
				if (this.formData.userType == 0) {
					delete this.formData.ballTeamNm
					delete this.formData.ballTeamType
				}
				if (!verifyForm(this.formData)) return // 调bug关掉校验
				if (!checkFontRule(this.formData.phone, '0')) return
				// if (!checkFontRule(this.formData.identityCardNo, '1')) return
				if (this.formData.email) {
					if (!checkFontRule(this.formData.email, '2')) return
				}
				uni.showLoading({mask:true});
				if (this.formData._id) {
					const parm = {}
					for (let k in this.formData) {
						if (k !== '_id') {
							parm[k] = this.formData[k]
						}
					}
					return db.collection('user-MGMT').doc(this.formData._id).update(parm).then((res) => {
						uni.showToast({
							title: '修改成功'
						})
						uni.setStorage({
							key: 'userInfo',
							data: _this.formData||{},
							success: function () {
								console.log('success');
							}
						})
						setTimeout(() => uni.navigateBack(), 1228)
						uni.hideLoading()
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
						uni.hideLoading()
					})
				} else {
					const parm = {
						phone: this.formData.phone
						// identityCardNo: this.formData.identityCardNo
					}
					cheackUser(parm,'reg').then(res => {
						console.log(res)
						if (!res.fla) {
							const parm = {
								userStatus: '1', // 用户状态 0待审批，1通过，2退回
								userType: '0', // 0 会员 1 球员 2负责人
								deleted_at: null,
								created_date: new Date().getTime(),
								updated_date: null,
								created_by: this.formData.userNm
							}
							const value = {
								...this.formData,
								...parm
							}
								
							if (res.data) {
								return db.collection('user-MGMT').doc(res.data._id).update(value).then((res) => {
									uni.showToast({
										title: '提交成功'
									})
									uni.setStorage({
										key: 'userInfo',
										data: _this.formData||{},
										success: function () {
											console.log('success');
										}
									})
									setTimeout(() => uni.navigateBack(), 1228)
									uni.hideLoading()
								}).catch((err) => {
									uni.showModal({
										content: err.message || '请求服务失败',
										showCancel: false
									})
									uni.hideLoading()
								})
							} else {
								value.password = value.phone.substring(5,11)
								return db.collection('user-MGMT').add(value).then((res) => {
									uni.showToast({
										title: '新增成功'
									})
									setTimeout(() => uni.navigateBack(), 1228)
									uni.hideLoading()
								}).catch((err) => {
									uni.showModal({
										content: err.message || '请求服务失败',
										showCancel: false
									})
									uni.hideLoading()
								})
							}
						} else {
							uni.hideLoading()
						}
					})
				}
			}
		}
	}
</script>

<style>
	.reg-page {}
	.form-sty  .uni-file-picker {
		display: inline-block;
		width: 50%;
	}
	.input-title {
		width: 43%;
		display: inline-block;
		vertical-align: top;
	}

	.img-sty {
		width: 60%;
		height: 68px;
		display: inline-block;
	}

	.input-sty {
		width: 57%;
		display: inline-block;
		vertical-align: middle;
	}
	.is-disabled {
		width: 50%;
		color: #888;
	}
	.form-sty {
		width: 100%;
		height: 70px;
		border-bottom: 1px solid #dcdfe6;
		line-height: 70px;
		padding: 0 5px;
	}

	.btn-area {
		width: 150px;
		text-align: center;
		flex: 1;
	}

	.btn-sty {
		width: 150px;
		height: 38px;
		color: #fc993b;
		background: #ffffff;
		border: 1px solid #fc993b;
		border-radius: 20px;
		line-height: 38px;
		margin: 0 auto;
	}
	.bi-shu-sty::before {
		content: '*';
		position: relative;
		top: 0;
		left: 0;
		color: red;
	}
</style>
<style lang="scss">
</style>